document.addEventListener('DOMContentLoaded', () => {
    // 获取DOM元素
    const employeeTable = document.getElementById('employeeTable');
    const searchBtn = document.getElementById('searchBtn');
    const addEmployeeBtn = document.getElementById('addEmployeeBtn');
    const prevPageBtn = document.getElementById('prevPageBtn');
    const nextPageBtn = document.getElementById('nextPageBtn');
    const pageSizeSelect = document.getElementById('pageSize');
    const employeeModal = document.getElementById('employeeModal');
    const employeeForm = document.getElementById('employeeForm');
    const closeModalBtn = document.getElementById('closeModalBtn');
    const cancelModalBtn = document.getElementById('cancelModalBtn');

    // 初始化变量
    let currentPage = 1;
    let totalPages = 1;
    const token = localStorage.getItem('token');

    // 检查登录状态
    if (!token) {
        window.location.href = 'index.html';
        return;
    }

    // 设置当前用户
    const currentUser = JSON.parse(localStorage.getItem('user'));
    if (currentUser && currentUser.name) {
        document.getElementById('currentUser').textContent = currentUser.name;
    }

    // 加载员工数据
    loadEmployees();

    // 事件监听
    searchBtn.addEventListener('click', () => {
        currentPage = 1;
        loadEmployees();
        
    });

    addEmployeeBtn.addEventListener('click', showAddModal);
    prevPageBtn.addEventListener('click', prevPage);
    nextPageBtn.addEventListener('click', nextPage);
    pageSizeSelect.addEventListener('change', () => {
        currentPage = 1;
        loadEmployees();
    });

    closeModalBtn.addEventListener('click', closeModal);
    cancelModalBtn.addEventListener('click', closeModal);
    employeeForm.addEventListener('submit', handleEmployeeFormSubmit);

    document.querySelectorAll('.sidebar-menu li').forEach(item => {
        item.addEventListener('click', function() {
            const page = this.getAttribute('data-page');
            navigateToPage(page);
        });
    });

            function navigateToPage(page) {
            console.log('Navigating to page:', page);
            if (page === 'dashboard') {
                window.location.href = 'dashboard.html';
            } else if (page === 'employees') {
                window.location.href = 'employees.html';
            } else if (page === 'products') {
                window.location.href = 'product.html';
            } else if (page === 'activities') {
                window.location.href = 'activities.html';
            } else if (page === 'settings') {
                window.location.href = 'settings.html';
            }else if (page === 'ai-chat') {
                window.location.href = 'ai-chat.html';
            }else if (page === 'expert') {
                window.location.href = 'expert.html';
            }else if(page === 'order'){
                window.location.href = 'order.html';
            }else if(page === 'farm-management'){
                window.location.href = 'farm.html';
            }
        }





    // 退出登录
    document.getElementById('logoutBtn').addEventListener('click', logout);

    // 加载员工数据
    async function loadEmployees() {
        showLoading();

        try {
            const params = new URLSearchParams({
                name: document.getElementById('searchName').value,
                page: currentPage,
                pageSize: pageSizeSelect.value
            });

            const response = await fetch(`http://192.168.8.128:8080/admin/employee/page?${params}`, {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            });

            if (!response.ok) {
                throw new Error('获取员工数据失败');
            }

            const data = await response.json();

            if (data.code === 1) {
                renderTable(data.data.records);
                updatePagination(data.data.total);
            } else {
                throw new Error(data.msg || '获取员工数据失败');
            }
        } catch (error) {
            console.error('加载员工数据错误:', error);
            showToast(error.message, 'error');
        } finally {
            hideLoading();
        }
    }

    // 渲染表格
    function renderTable(employees) {
        const tbody = employeeTable.querySelector('tbody');
        tbody.innerHTML = '';

        employees.forEach(emp => {
            const tr = document.createElement('tr');

            tr.innerHTML = `
                <td>${emp.name}</td>
                <td>${emp.username}</td>
                <td>${emp.phone}</td>
                <td class="${emp.status ? 'status-active' : 'status-inactive'}">
                    ${emp.status ? '启用' : '禁用'}
                </td>
                <td>
                    <button class="btn ${emp.status ? 'danger-btn' : 'success-btn'}" 
                            data-id="${emp.id}" data-status="${emp.status}">
                        ${emp.status ? '禁用' : '启用'}
                    </button>
                    <button class="btn primary-btn edit-btn" data-id="${emp.id}">
                        <i class="fas fa-edit"></i> 编辑
                    </button>
                    <button class="btn danger-btn delete-btn" data-id="${emp.id}">
                        <i class="fas fa-trash"></i> 删除
                    </button>
                </td>
            `;

            tbody.appendChild(tr);
        });

        // 添加按钮事件
        document.querySelectorAll('.edit-btn').forEach(btn => {
            btn.addEventListener('click', () => showEditModal(btn.dataset.id));
        });

        document.querySelectorAll('.delete-btn').forEach(btn => {
            btn.addEventListener('click', () => deleteEmployee(btn.dataset.id));
        });

        document.querySelectorAll('[data-status]').forEach(btn => {
            btn.addEventListener('click', () => toggleStatus(
                btn.dataset.id,
                parseInt(btn.dataset.status)
            ));
        });
    }

    // 分页控制
    function updatePagination(total) {
        const pageSize = parseInt(pageSizeSelect.value);
        totalPages = Math.ceil(total / pageSize);

        document.getElementById('currentPage').textContent =
            `第 ${currentPage} 页 / 共 ${totalPages} 页`;

        prevPageBtn.disabled = currentPage <= 1;
        nextPageBtn.disabled = currentPage >= totalPages;
    }

    function prevPage() {
        if (currentPage > 1) {
            currentPage--;
            loadEmployees();
        }
    }

    function nextPage() {
        if (currentPage < totalPages) {
            currentPage++;
            loadEmployees();
        }
    }

    // 员工状态切换
    async function toggleStatus(id, currentStatus) {
        if (!confirm(`确定要${currentStatus ? '禁用' : '启用'}该员工吗？`)) return;

        try {
            const response = await fetch(
                `http://localhost:8080/admin/employee/status/${currentStatus ? 0 : 1}?id=${id}`,
                {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                }
            );

            if (response.ok) {
                loadEmployees();
                showToast(`员工已${currentStatus ? '禁用' : '启用'}`, 'success');
            } else {
                throw new Error('操作失败');
            }
        } catch (error) {
            console.error('状态切换错误:', error);
            showToast(error.message, 'error');
        }
    }

    // 删除员工
    async function deleteEmployee(id) {
        if (!confirm('确定要删除该员工吗？此操作不可撤销！')) return;

        try {
            const response = await fetch(
                `http://localhost:8080/admin/employee/${id}`,
                {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                }
            );

            if (response.ok) {
                loadEmployees();
                showToast('员工已删除', 'success');
            } else {
                throw new Error('删除失败');
            }
        } catch (error) {
            console.error('删除员工错误:', error);
            showToast(error.message, 'error');
        }
    }

    // 显示新增模态框
    function showAddModal() {
        document.getElementById('modalTitle').textContent = '新增员工';
        document.getElementById('employeeId').value = '';
        employeeForm.reset();
        employeeModal.style.display = 'flex';
    }

    // 显示编辑模态框
    async function showEditModal(id) {
        showLoading();

        try {
            const response = await fetch(
                `http://localhost:8080/admin/employee/${id}`,
                {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                }
            );

            if (!response.ok) {
                throw new Error('获取员工数据失败');
            }

            const data = await response.json();

            if (data.code === 1) {
                document.getElementById('modalTitle').textContent = '编辑员工';
                document.getElementById('employeeId').value = data.data.id;
                document.getElementById('modalUsername').value = data.data.username;
                document.getElementById('modalName').value = data.data.name;
                document.getElementById('modalPhone').value = data.data.phone;
                document.getElementById('modalSex').value = data.data.sex;
                document.getElementById('modalIdNumber').value = data.data.idNumber;

                employeeModal.style.display = 'flex';
            } else {
                throw new Error(data.msg || '获取员工数据失败');
            }
        } catch (error) {
            console.error('获取员工错误:', error);
            showToast(error.message, 'error');
        } finally {
            hideLoading();
        }
    }

    // 关闭模态框
    function closeModal() {
        employeeModal.style.display = 'none';
    }

    // 处理表单提交
    async function handleEmployeeFormSubmit(e) {
        e.preventDefault();
        showLoading();

        const formData = {
            username: document.getElementById('modalUsername').value,
            name: document.getElementById('modalName').value,
            phone: document.getElementById('modalPhone').value,
            sex: document.getElementById('modalSex').value,
            idNumber: document.getElementById('modalIdNumber').value
        };

        const id = document.getElementById('employeeId').value;
        const isEdit = !!id;

        try {
            const url = isEdit ?
                `http://localhost:8080/admin/employee/${id}` :
                'http://localhost:8080/admin/employee';

            const method = isEdit ? 'PUT' : 'POST';

            if (isEdit) {
                formData.id = id;
            }

            const response = await fetch(url, {
                method,
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify(formData)
            });

            if (!response.ok) {
                throw new Error(isEdit ? '更新失败' : '添加失败');
            }

            const data = await response.json();

            if (data.code === 1) {
                closeModal();
                loadEmployees();
                showToast(
                    `员工${isEdit ? '更新' : '添加'}成功`,
                    'success'
                );
            } else {
                throw new Error(data.msg || (isEdit ? '更新失败' : '添加失败'));
            }
        } catch (error) {
            console.error('表单提交错误:', error);
            showToast(error.message, 'error');
        } finally {
            hideLoading();
        }
    }

    // 退出登录
    async function logout() {
        try {
            await fetch('http://localhost:8080/admin/employee/logout', {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            });

            localStorage.removeItem('token');
            localStorage.removeItem('user');
            window.location.href = 'index.html';
        } catch (error) {
            console.error('退出登录错误:', error);
            showToast('退出失败', 'error');
        }
    }

});